import { createRouter, createWebHistory } from 'vue-router'
import { useStore } from 'vuex'
import Login from '../views/Login.vue'
import MainLayout from '../layouts/MainLayout.vue'
import Dashboard from '../views/Dashboard.vue'
import Profile from '../views/Profile.vue'
import Settings from '../views/Settings.vue'
import RoomManagement from '../views/RoomManagement.vue'
import ProductManagement from '../views/ProductManagement.vue'
import History from '../views/History.vue'
import Report from '@/views/Report.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        redirect: '/dashboard'
      },
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard
      },
      {
        path: 'profile',
        name: 'Profile',
        component: Profile
      },
      {
        path: 'settings',
        name: 'Settings',
        component: Settings,
        meta: {
          requiresAuth: true,
          title: '系统设置'
        }
      },
      {
        path: 'rooms',
        name: 'RoomManagement',
        component: RoomManagement
      },
      {
        path: 'products',
        name: 'ProductManagement',
        component: ProductManagement,
        meta: {
          title: '商品管理',
          requiresAuth: true
        }
      },
      {
        path: 'history',
        name: 'History',
        component: History
      },
      {
        path: 'report',
        name: 'Report',
        component: Report,
        meta: { 
          requiresAuth: true,
          title: '营业报表'
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory('./'),
  routes
})

// 需要登录才能访问的路由
const protectedRoutes = [
  '/dashboard',
  '/rooms',
  '/products',
  '/history',
  '/profile',
  '/settings'
]

router.beforeEach((to, from, next) => {
  // 检查是否是需要保护的路由
  if (protectedRoutes.includes(to.path)) {
    const token = localStorage.getItem('token')
    if (!token) {
      // 未登录，跳转到登录页面
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存原目标路由
      })
      return
    }
  }
  
  // 如果已登录用户访问登录页，重定向到首页
  if (to.path === '/login' && localStorage.getItem('token')) {
    next('/dashboard')
    return
  }

  // 其他情况正常跳转
  next()
})

export default router 